/**
 * 物料选项
 * @author Canaan
 * @date 2019/8/14 14:28
 */
export default {

  state: {
    materialOptions: {
      refNum: 0,          //被组件引用次数
      loading: false,     //数据是否加载中
      options: []         //具体的选项列表
    }
  },

  actions: {
    loadMaterialOptions({commit, state}, {vue, materialId, searchKey}) {

      //如果没有被人引用，那么不加载数据
      if (state.materialOptions.refNum <= 0) {
        return;
      }

      //如果正在加，就不处理
      if (state.materialOptions.loading) {
        return;
      }

      let brandId;
      if (!state.userContext.id) {
        return; //当前用户还未加载
      } else if (state.userContext.role === 'BRAND') {
        brandId = state.userContext.brand.id;
      } else if (state.userContext.role === 'STORE') {
        brandId = state.userContext.store.brand.id;
      }

      if (!brandId) {
        return;
      }

      commit('materialOptions', {cmd: "loading", val: true});

      vue.$ajax.get('material/paging', {
          params: {
            id: materialId,
            brandId: brandId,
            searchKey: searchKey
          }
        }
      ).then(res => {
        commit('materialOptions', {cmd: "loading", val: false});
        if (res.code !== 'ok') {
          throw res.msg;
        }
        commit('materialOptions', {cmd: "options", val: res.data.rows || []});
      });

    }
  },
  mutations: {
    clearMaterialOptions({materialOptions}) {
      materialOptions.options = [];
    },
    materialOptions({materialOptions}, {cmd, val}) {
      switch (cmd) {
        case "loading":
          materialOptions.loading = val;
          break;
        case "options":
          materialOptions.options = val;
          break;
        case "minusRef":
          materialOptions.refNum = Math.max(0, materialOptions.refNum - 1);
          break;
        case "plusRef":
          materialOptions.refNum++;
          break;
        default:
          throw "materialOptions 未知的命令" + cmd;
      }
    }
  }


}
